package com.example.myapplication.navigation.fragment_login;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.SavedStateHandle;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavBackStackEntry;
import androidx.navigation.NavController;
import androidx.navigation.NavOptions;
import androidx.navigation.fragment.NavHostFragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.myapplication.R;
import com.example.myapplication.bean.User;
import com.example.myapplication.databinding.viewmodel.UserViewModel;
import com.example.myapplication.databinding.FragmentProfileBinding;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class ProfileFragment extends Fragment {

    FragmentProfileBinding binding;
    private UserViewModel userViewModel;
    NavController navController;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        navController = NavHostFragment.findNavController(this);

        NavBackStackEntry navBackStackEntry = navController.getCurrentBackStackEntry();
        SavedStateHandle savedStateHandle = navBackStackEntry.getSavedStateHandle();

        MutableLiveData<Boolean> data = savedStateHandle.getLiveData(LoginFragment.LOGIN_SUCCESSFUL);
        data.observe(navBackStackEntry, aBoolean -> {
            if (!aBoolean) {
                int startDestination = navController.getGraph().getStartDestination();
                NavOptions navOptions = new NavOptions.Builder()
                        .setPopUpTo(startDestination, true)
                        .build();
                navController.navigate(startDestination, null, navOptions);
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        binding = FragmentProfileBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        userViewModel = new ViewModelProvider(requireActivity()).get(UserViewModel.class);
        userViewModel.mUserLiveData.observe(getViewLifecycleOwner(), user -> {
            if (user == null) {
                navController.navigate(R.id.loginFragment);
            } else {
                showUserInfo(user);
            }
        });
    }

    private void showUserInfo(User user){
        binding.setUser(user);
    }
}
